const DB = require('../../utils/db');
const { cosDelete, cosUpload } = require('../../utils/oss');
const path = require('path');

// 文件夹名称
let ossDirectory = 'setting';

module.exports = {
	list: async () => {
		let sql = `select *, date_format(createTime,'%Y-%m-%d %H:%i:%s') createTime,
            date_format(updateTime,'%Y-%m-%d %H:%i:%s') updateTime from t_setting order by id asc`;

		let [list] = await DB.query(sql);
		return list;
	},
	add: async (id, url, filename, title) => {
		let [list] = await DB.query('select * from t_setting where id=?', [id]);

		if (list.length) {
			throw new Error('当前路由已有图片');
		}

		// 上传oss
		let { Location } = await cosUpload(ossDirectory, filename);

		// oss 全路径
		let fullUrl = 'https://' + Location;

		await DB.query('insert into t_setting (id, url,fullUrl,title) values(?,?,?,?)', [id, url, fullUrl, title]);
	},
	edit: async (id, url, filename, title) => {
		let [list] = await DB.query('select url from t_setting where id=?', [id]);

		// 未修改封面，就不上传oss
		if (list[0].url == url) {
			await DB.query(`update t_setting set  title=? where id =?`, [title, id]);
		} else {
			await cosDelete(ossDirectory, path.basename(list[0].url));
			// 上传oss
			let { Location } = await cosUpload(ossDirectory, filename);
			// oss 全路径
			let fullUrl = 'https://' + Location;
			// 修改新图片
			await DB.query(`update t_setting set id=?, url=?,fullUrl=?,title=? where id =?`, [id, url, fullUrl, title, id]);
		}
	},
	detail: async (id) => {
		const [list] = await DB.query(`select * from t_setting where id =?`, [id]);
		return list[0];
	},
	del: async (id) => {
		let [list] = await DB.query('select url from t_setting where id=?', [id]);
		// 删除oss 图片
		await cosDelete(ossDirectory, path.basename(list[0].url));
		await DB.query(`delete from t_setting where id =?`, [id]);
		return true;
	}
};
